import { ref, computed } from "vue";
import { defineStore } from "pinia";
import Router from "../router/index.js";

export const useCounterStore = defineStore("counter", {
  state: () => {
    return {
      windowWidth: 0,
      windowHeight: 0,
      isCollapse: false, //菜单折叠
      menuWidth: "200px", //左侧菜单宽度
      userInfo: {}, //用户信息
      configInfo: {}, //公司信息
      tagList: [], //路由标签
      tagType: true, //是否显示标签
      path: "", //当前路由
      menuList: [],
    };
  },
  getters: {
    // 表格高度
    tableHeight(state) {
      if (state.tagType) {
        return state.windowHeight - 205;
      } else {
        return state.windowHeight - 160;
      }
    },
    menuJson(state) {
      return JSON.stringify(state.menuList);
    },
  },
  actions: {
    SET_TAGITEM(obj) {
      let arrData = sessionStorage.getItem("p_tag_list");
      if (obj) {
        if (arrData) {
          this.tagList = JSON.parse(arrData);
          if (
            !this.tagList.some((item) => {
              return item.path == obj.path;
            })
          ) {
            this.tagList.push(obj);
          }
        } else {
          if (
            !this.tagList.some((item) => {
              return item.path == obj.path;
            })
          ) {
            this.tagList.push(obj);
          }
        }
        if (this.tagList.length > 20) {
          this.tagList.shift();
        }
      } else {
        const route = useRoute();

        if (arrData) {
          this.tagList = JSON.parse(arrData);
        } else {
          let arr = localStorage.getItem("manpu_menuList");
          let menuInfo = searchTagData(JSON.parse(arr), route.path);

          let obj = {
            title: menuInfo.title,
            path: route.path,
          };

          if (
            !this.tagList.some((item) => {
              return item.path == obj.path;
            })
          ) {
            this.tagList.push(obj);
          }
        }
      }
      sessionStorage.setItem("p_tag_list", JSON.stringify(this.tagList));
    },
    DEL_TAG(path, i) {
      this.tagList.splice(i, 1);
      sessionStorage.setItem("p_tag_list", JSON.stringify(this.tagList));
      if (path == this.path) {
        if (i > 0) {
          Router.push(this.tagList[i - 1].path);
          this.path = this.tagList[i - 1].path;
        } else {
          Router.push(this.tagList[i].path);
          this.path = this.tagList[i].path;
        }
      }
    },
    SET_MENU() {
      let arr = localStorage.getItem("manpu_menuList");
      if (!arr || arr == "undefined") return console.log("菜单不存在");
      this.menuList = JSON.parse(arr);
    },
  },
});

function searchTagData(arr, path) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].url == path) {
      console.log(arr[i]);
      return arr[i];
    } else {
      if (arr[i].children) {
        let value = searchTagData(arr[i].children, path);
        if (value) return value;
      }
    }
  }
  return null;
}
